#include "logger.h"
#include <ctime>
#include <iomanip>
#include <iostream>
#include "../db_manager/conf/config.h"
Logger &Logger::GetInstance()
{
    static Logger instance;
    return instance;
}

Logger::Logger()
{
    try
    {
        // 1. 获取配置实例
        Config &config = Config::getInstance();

        // 2. 获取可执行文件的根目录
        std::string exe_dir = ".";
        if (exe_dir.empty())
        {
            // 降级到在当前工作目录创建日志
            std::cerr << "Warning: Could not get executable directory. Logging to current working directory." << std::endl;
            exe_dir = "."; // 使用当前目录作为备选方案
        }

        // 3. 从配置文件读取相对路径和文件名
        std::string log_dir_relative = config.GetValue<std::string>("log_dir", "logs");
        std::string log_filename = config.GetValue<std::string>("log_file", "db.log");

        // 4. 使用 std::filesystem 安全地拼接路径
        // 这是最关键的一步。`operator/` 会自动处理平台相关的路径分隔符 ('\' 或 '/')
        std::filesystem::path log_dir_full_path = std::filesystem::path(exe_dir) / log_dir_relative;
        std::filesystem::path log_file_full_path = log_dir_full_path / log_filename;

        // 5. 在打开文件前，创建日志目录（如果它不存在）
        std::filesystem::create_directories(log_dir_full_path);

        // 6. 使用完整的、绝对的路径打开文件
        log_file_.open(log_file_full_path, std::ios::app);

        if (!log_file_.is_open())
        {
            std::cerr << "Fatal Error: Failed to open log file at: " << log_file_full_path << std::endl;
        }
    }
    catch (const std::exception &e)
    {
        std::cerr << "Fatal Error in Logger initialization: " << e.what() << std::endl;
    }
}

Logger::~Logger()
{
    if (log_file_.is_open())
        log_file_.close();
}

void Logger::Info(const std::string &msg)
{
    auto now = std::time(nullptr);
    log_file_ << "[" << std::put_time(std::localtime(&now), "%Y-%m-%d %H:%M:%S")
              << "][INFO] " << msg << std::endl;
}

void Logger::Error(const std::string &msg)
{
    auto now = std::time(nullptr);
    log_file_ << "[" << std::put_time(std::localtime(&now), "%Y-%m-%d %H:%M:%S")
              << "][ERROR] " << msg << std::endl;
}

void Logger::Debug(const std::string &msg)
{
    auto now = std::time(nullptr);
    log_file_ << "[" << std::put_time(std::localtime(&now), "%Y-%m-%d %H:%M:%S")
              << "][DEBUG] " << msg << std::endl;
}
void Logger::Warning(const std::string &msg)
{
    auto now = std::time(nullptr);
    log_file_ << "[" << std::put_time(std::localtime(&now), "%Y-%m-%d %H:%M:%S")
              << "][WARNING] " << msg << std::endl;
}